package com.ld.control.exception;

import com.ld.control.common.ResultResponse;
import com.ld.control.sysenum.ResultResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * 系统异常 预期以外异常
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public ResultResponse<ResultResponseEnum> handleBusinessException(BusinessException ex) {
        log.error("BusinessException：{}，code:{}", ex.getMessage(), ex.getCode());
        return ResultResponse.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 运行时异常 预期以外异常
     * @param ex
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public ResultResponse<ResultResponseEnum> handleRuntimeException(RuntimeException ex) {
        log.error("运行时异常：", ex);
        return ResultResponse.error("运行发生异常:" + ex.getMessage());
    }

    /**
     * 系统异常 预期以外异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    public ResultResponse<ResultResponseEnum> handleException(Exception ex) {
        log.error("系统异常：", ex);
        return ResultResponse.error("服务器异常:" + ex.getMessage());
    }
}
